package com.gtenacg.fileservice.controller;

import com.gtenacg.fileservice.service.DownloadService;
import com.gtenacg.fileservice.util.FileUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
public class FileRetrievalController {

    final DownloadService downloadService;
    final FileUtil fileUtil;

    @GetMapping("/download")
    public void download(@RequestParam String fileName, HttpServletResponse response) {
        log.info("获取文件 {}", fileName);

        InputStream is = downloadService.getFileInputStream(fileName);
        String contentType = fileUtil.getContentType(fileUtil.getFileExtension(fileName));

        if (is != null) {
            try {
                // 设置响应头
                response.setContentType(contentType);
                // 设置下载信息，确保文件名在浏览器中正确显示（支持中文和特殊字符）
                if (contentType.startsWith("application")) {
                    String[] split = fileName.split("/");
                    String originalFilename = split[split.length - 1];
                    // 无后缀名，认定为文件夹，添加zip标识
                    if (fileUtil.getFileExtension(originalFilename).isEmpty()) {
                        originalFilename = originalFilename + "-zip.zip";
                    }
                    String encodedFilename = URLEncoder.encode(originalFilename, StandardCharsets.UTF_8);
                    response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFilename + "\"");
                }

                // 写入响应体
                ServletOutputStream outputStream = response.getOutputStream();
                FileCopyUtils.copy(is, outputStream);

            } catch (IOException e) {
                log.error("发送文件时发生错误", e);
                // 发送错误响应，但在这里通常不会发送文件数据
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            log.error("请求失败！！！");
            // 发送错误响应
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    @GetMapping("/list")
    public List<String> list(@RequestParam String filePath, @RequestParam(required = false) Boolean getFile) {
        log.info("获取路径为 {} 的文件列表", filePath);

        List<String> fileList = null;
        if (getFile == null) {
            fileList = downloadService.getFileList(filePath,(file) -> true);
        }else if (getFile) {
            fileList = downloadService.getFileList(filePath,File::isFile);
        } else {
            fileList = downloadService.getFileList(filePath,File::isDirectory);
        }

        return fileList;
    }



}
